package cn.stylefeng.guns.modular.weixin.handler;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.builder.outxml.TextBuilder;
import org.springframework.stereotype.*;
import cn.stylefeng.guns.modular.recy.service.*;
import org.springframework.beans.factory.annotation.*;
import cn.stylefeng.guns.modular.system.service.*;
import me.chanjar.weixin.mp.api.*;
import me.chanjar.weixin.common.session.*;
import me.chanjar.weixin.mp.bean.message.*;
import cn.stylefeng.guns.modular.recy.entity.*;
import cn.stylefeng.guns.modular.recy.utils.*;
import org.apache.commons.lang3.*;
import org.apache.commons.lang3.math.*;
import cn.stylefeng.guns.modular.weixin.utils.*;
import me.chanjar.weixin.common.error.*;
import me.chanjar.weixin.mp.bean.result.*;
import cn.stylefeng.guns.modular.system.entity.*;

import java.util.stream.*;
import java.util.*;

@Component
public class SubscribeHandler extends AbstractHandler
{
    @Autowired
    private WechatUserService wechatUserService;
    @Autowired
    private DictService dictService;
    @Autowired
    private UserNoCreator userNoCreator;

    @Autowired
    private BinsService binsService;
    @Autowired
    private OrderFormService orderFormService;

    public WxMpXmlOutMessage handle(final WxMpXmlMessage wxMessage, final Map<String, Object> context, final WxMpService weixinService, final WxSessionManager sessionManager) throws WxErrorException {
        this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());
        String msg = "";//this.getMsg("关注消息", new Object[0]);
        try {
            final WxMpUser userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser(), (String)null);
            if (userWxInfo != null) {
                WechatUser user = this.wechatUserService.findByOpenId(userWxInfo.getOpenId());
                if (user == null) {
                    user = new WechatUser();
                    user.setOpenId(userWxInfo.getOpenId());
                    user.setAvatarUrl(userWxInfo.getHeadImgUrl());
                    user.setWechatNickName(userWxInfo.getNickname());
                    user.setUserNo(Long.valueOf(this.userNoCreator.incrementAndGet()));
                    user.setStatus(DictUtils.me().id("wxuser_status::common"));
                    user.setCreateTime(new Date());
                    final String mpCode = WxUtils.getMpCode(wxMessage.getToUser());
                    if (!StringUtils.isAnyBlank(new CharSequence[] { mpCode })) {
                        user.setMpCode(mpCode);
                    }
                    this.wechatUserService.save(user);
                    msg = "欢迎关注昌佳智能分类公众号！";
                }
                if(user!=null){
                    if(StringUtils.isBlank(user.getPhone()) && StringUtils.isBlank(user.getRemark())) {
                        msg += "<a href=\"" + weixinService.oauth2buildAuthorizationUrl(
                                String.format(WxUtils.MP_DOMAIN + "/app/completeUserInfo"),
                                WxConsts.OAuth2Scope.SNSAPI_USERINFO, null) + "\">您的个人信息尚未完善，请点击前往完善。</a>";
                    }
                }
                final String eventKey = wxMessage.getEventKey();
                if (StringUtils.startsWith((CharSequence)eventKey, (CharSequence)"qrscene_")) {
                    Long binsId = NumberUtils.toLong(eventKey.replace("qrscene_", ""),-1l);
                    if(!Objects.equals(binsId,-1l)){
                        Bins bins = this.binsService.getById(binsId);
                        if(bins!=null) {
                            QueryWrapper<OrderForm> queryWrapper = new QueryWrapper<>();
                            queryWrapper.lambda().eq(OrderForm::getBinsId,binsId).eq(OrderForm::getUserId,user.getId()).eq(OrderForm::getState,DictUtils.me().id("order_form_state::create"));
                            List<OrderForm> orderFormList = this.orderFormService.list(queryWrapper);
                            if(orderFormList.size()<=0) {
                                OrderForm orderForm = OrderForm.builder().userId(user.getId()).binsId(binsId).createTime(new DateTime()).state(DictUtils.me().id("order_form_state::create")).build();
                                orderForm.insert();
                            }

                        }
                    }


                }
            }
        }
        catch (WxErrorException e) {
            e.printStackTrace();
            if (e.getError().getErrorCode() == 48001) {
                this.logger.info("该公众号没有获取用户信息权限！");
            }
        }
        WxMpXmlOutMessage responseResult = null;
        try {
            responseResult = this.handleSpecial(wxMessage);
        }
        catch (Exception e2) {
            this.logger.error(e2.getMessage(), (Throwable)e2);
        }
        if (responseResult != null) {
            return responseResult;
        }
        try {
            WxMpXmlOutTextMessage build = new TextBuilder().toUser(wxMessage.getFromUser()).content(msg).build();
            return build;
        }
        catch (Exception e2) {
            this.logger.error(e2.getMessage(), e2);
            return null;
        }
    }
    
    private WxMpXmlOutMessage handleSpecial(final WxMpXmlMessage wxMessage) throws Exception {
        return null;
    }
    
    public String getMsg(final String msgName, final Object... values) {
        final List<Dict> textList = this.dictService.selectByTypeCode("text_list");
        final Map<String, Dict> textMap = textList.stream().collect(Collectors.toMap(dict -> dict.getName(), dict -> dict));
        final Dict textDict = textMap.get(msgName);
        final String msgTemplate = textDict.getCode();
        return MsgHandler.parseMsgFormat(msgTemplate, values);
    }
}
